#include "package.h"

unsigned int POLYNOMIAL = 0xEDB88320;
int have_table = 0;
unsigned int table[256];

Package::Package() {
	ident = 0;
	version = 0;
	type = 0;
	sessinId = 0;
	crc32 = 0;
	size = 0;
	timestamp = 0;
}

Package::~Package() {

}

void Package::init(char* buffer) {
	ident = *((unsigned short*)(buffer));
	memset(&version, *(unsigned char*)(buffer + 2), sizeof(unsigned char));
	memset(&type, *(unsigned char*)(buffer + 3), sizeof(unsigned char));
	sessinId = *((unsigned int*)(buffer + 4));
	timestamp = *((unsigned long long*)(buffer + 8));
	crc32 = *((unsigned int*)(buffer + 16));
	size = *((unsigned int*)(buffer + 20));

	//printf_s("%d %c %c %d %d %d\n", ident, version, type, sessinId, crc32, size);
}

unsigned short Package::getIdentValue() {
	return ident;
}

unsigned char Package::getVersionValue() {
	return version;
}

unsigned char Package::getTypeValue() {
	return type;
}

unsigned int Package::getSessinIdValue() {
	return sessinId;
}

unsigned int Package::getCrc32Value() {
	return crc32;
}

unsigned int Package::getSizeValue() {
	return size;
}

unsigned long long Package::getTimestampValue() {
	return timestamp;
}

void Package::inbody(char* buffer) {

}

void Package::setIdentValue(unsigned short value) {
	ident = value;
}

void Package::setVersionValue(unsigned char value) {
	version = value;
}

void Package::setTypeValue(unsigned char value) {
	type = value;
}

void Package::setSessinIdValue(unsigned int value) {
	sessinId = value;
}

void Package::setCrc32Value(unsigned int value) {
	crc32 = value;
}

void Package::setSizeValue(unsigned int value) {
	size = value;
}

void Package::setTimestampValue(unsigned long long value) {
	timestamp = value;
}

void Package::make_table()
{
	int i, j, crc;
	have_table = 1;
	for (i = 0; i < 256; i++)
		for (j = 0, table[i] = i; j < 8; j++)
			table[i] = (table[i] >> 1) ^ ((table[i] & 1) ? POLYNOMIAL : 0);
}


unsigned int Package::getCrc32(unsigned int crc, char* buff, int len)
{
	if (!have_table) make_table();
	crc = ~crc;
	for (int i = 0; i < len; i++)
		crc = (crc >> 8) ^ table[(crc ^ buff[i]) & 0xff];
	return ~crc;
}
